<?php

class Core_Api_Setting
{
	/**
	 * get setting
	 * @param string $name
	 * @param string $default
	 * @param int $site_id
	 */
	public function getSetting($name, $default = null, $site_id = null)
	{
		if (null == $site_id)
		{
			$site_id = Nuo::getSiteId();
		}

		$db = Zend_Db_Table::getDefaultAdapter();

		$table = Nuo::getTableName('core_settings');
		$row = $db -> fetchRow("SELECT * FROM $table where name='$name' and site_id=$site_id");

		// row exists?
		if (is_object($row))
		{
			return $row -> value;
		}
		return $default;
	}

	/**
	 * @param string $name
	 * @param string $value
	 * @param int $site_id
	 */
	public function setSetting($name, $value, $site_id = null)
	{
		if (null == $site_id)
		{
			$site_id = Nuo::getSiteId();
		}

		$db = Zend_Db_Table::getDefaultAdapter();
		$table = self::getTableName('core_settings');
		$row = $db -> fetchRow("SELECT * FROM $table where name='$name' and site_id=$site_id");

		// row exists?
		if (is_null($row))
		{
			$db -> insert($table, array(
					'value' => $value,
					'name' => $name,
					'site_id' => $site_id
			));
		}
		else
		{
			$db -> update($table, array('value' => $value), array(
					'site_id=?' => $site_id,
					'name=?' => $name
			));
		}

	}

	/**
	 * read seting from file
	 * @param string $file etc: /boot.php
	 * @return array
	 */
	static public function readFromFile($file)
	{
		$file = SETTING_PATH . $file;
		$data = null;
		if (is_readable($file))
		{
			$param = (
			include $file);
		}
		return (array)$data;
	}

	/**
	 * @param mixed $data
	 * @param string $file etc: /boot.php
	 * @return true/false
	 * @throws Exception
	 */
	static public function writeToFile($data, $file)
	{
		$file = SETTING_PATH . $file;
		@$fp = fopen($fp, 'w');
		if (!$fp)
		{
			throw new Exception("$file is not writeable. please set chmod 777.");
		}
		fwrite($fp, '<?php defined(NUO) or die("Access Denied."); return ' . var_export($data, true) . ';?>');
		fclose($fp);
	}
	
}
